<template>
    <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="角色名">
          <el-input v-model="searchObj.roleName" placeholder="角色名" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="margin-left: 20px;">
          <el-select v-model="searchObj.status" placeholder="状态" size="mini">
            <el-option label="有效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 10px;">
          <el-button  type="primary" icon="el-icon-search" size="mini" @click="fetchData" >查询</el-button>
        </el-form-item>
        <el-form-item style="margin-left: 10px;">
          <el-button type="default" @click="resetData" size="mini" icon="el-icon-refresh-right">清空</el-button>
        </el-form-item>
      </el-form>
      <!-- 工具按钮 -->
      <div style="display: flex;">
      <el-button class="btn-add" size="mini"  type="primary" @click="openDialogForm()" style="margin-left: 10px;" v-if="$hasBP('bnt.sysRole.add')">添加</el-button>
      <el-button class="btn-add" size="mini"  type="danger" @click="batchRemove()" v-if="$hasBP('bnt.sysRole.remove')" >批量删除</el-button>
    </div>
    </el-card>
    <el-table :data="list" stripe border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">
          {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色名" width="150" align="center"> </el-table-column>
      <el-table-column prop="roleCode" label="角色编码" width="200" align="center"> </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status === 1"
            @change="switchStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="effectiveTime" label="生效日期"  width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column prop="invalidTime" label="失效日期" width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column prop="description" label="备注" width="200"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"  width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" sortable :formatter="dateFormat"> </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180" v-if="$hasBP('bnt.sysRole.update') && $hasBP('bnt.sysRole.remove') && $hasBP('bnt.sysRole.assignAuth')">
        <template slot-scope="scope">
          <span style="font-size: 8px;color: #429ec9;cursor: pointer;" @click="openDialogForm(scope.row.id)" v-if="$hasBP('bnt.sysRole.update')">修改</span>
          <span style="font-size: 8px;color: #429ec9;margin-left: 10px;cursor: pointer;" @click="removeById(scope.row.id)" v-if="$hasBP('bnt.sysRole.remove')">删除</span>
          <span style="font-size: 8px;color: #429ec9;margin-left: 10px;cursor: pointer;" @click="showAssignMenu(scope.row)" v-if="$hasBP('bnt.sysRole.assignAuth')">分配权限</span>
          <!-- <el-button type="primary" icon="el-icon-edit" circle @click="openDialogForm(scope.row.id)"  v-if="$hasBP('bnt.sysRole.update')" ></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="removeById(scope.row.id)" v-if="$hasBP('bnt.sysRole.remove')"></el-button>
          <el-button type="warning" icon="el-icon-share" circle @click="showAssignMenu(scope.row)" v-if="$hasBP('bnt.sysRole.assignAuth')"></el-button> -->
        </template>
      </el-table-column>
    </el-table>
     <!-- 分页组件 -->
     <el-pagination :current-page="pageNum" :total="total" :page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]" style="padding: 30px 0; text-align: center;"
      layout="total,sizes,prev, pager, next, jumper" @size-change="changePageSize" @current-change="changeCurrentPage">
    </el-pagination>
    <!-- 添加修改弹出框 -->
    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible" top="40px" width="500px" @close="resetForm('form')">
      <el-form :model="form"  :rules="rules" ref="form" >
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" :label-width="formLabelWidth" prop="roleCode">
          <el-input v-model="form.roleCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="生效日期" :label-width="formLabelWidth">
            <el-date-picker
                v-model="form.effectiveTime"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期" :label-width="formLabelWidth" v-if="status===false">
            <el-date-picker
                v-model="form.invalidTime"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="description">
          <el-input v-model="form.description" autocomplete="off" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色弹出框 -->
    <el-dialog title="分配权限" :visible.sync="dialogAssignVisible" width="500px" top="40px" >
      <el-tree
        :data="sysMenuList"
        show-checkbox
        node-key="id"
        ref="tree"
        default-expand-all
        :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAuth()">确 定</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
import sysRoleApi from "@/api/system/sysRole";
import moment from "moment"
export default {
    data(){
        return{
            searchObj: {}, // 查询表单对象
            list: [], //用户列表
            total: 0, //总记录数
            pageNum: 1, //页码
            pageSize: 10, //每页记录数
            multipleSelection: [], //批量删除选中的记录列表
            dialogFormVisible: false,  //添加修改弹出框
            formLabelWidth: '100px',
            dialogFormTitle: '',
            status: false,
            form:{
                roleName: '',
                roleCode: '',
                status: 0,
                effectiveTime: '',
                invalidTime: '',
                description: ''
            },
            rules: {
                roleName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { max: 100, message: '长度在 100 个字符之内', trigger: 'blur' }
                ],
                roleCode: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {  max: 50, message: '长度在 50 个字符之内', trigger: 'blur' }
                ]
            },
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                    picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24);
                    picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', date);
                    }
                }]
            },
            dialogAssignVisible: false,
            sysMenuList:[],
            defaultProps: {
              children: 'children',
              label: 'name'
            },
            assignRoleId: '',
        }
    },
    created(){
        this.fetchData()
    },
    methods:{
      /*日期处理*/
      dateFormat:function(row,column){
        var date = row[column.property];
        if(date === undefined || date === null){
          return ''
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss")
      },
      showAssignMenu(row){
        this.dialogAssignVisible = true
        this.assignRoleId = row.id
        sysRoleApi.toAssign(row.id)
        .then(response =>{
          this.sysMenuList = response.data
          console.log(this.sysMenuList);
          let newArr=[]
          this.getCheckedIds(this.sysMenuList,newArr)
          console.log(newArr);
          this.$refs.tree.setCheckedKeys(newArr);
        })
        
      },
      //得到树形集合中所有呗选中的ids
      getCheckedIds(list,newArr){
        for (let i = 0; i < list.length; i++) {
          if(list[i].select && list[i].children.length === 0){
            newArr.push(list[i].id)
          }else if(list[i].children && list[i].children.length > 0){
            this.getCheckedIds(list[i].children,newArr)
          }
        }
      },
      
      // 保存权限列表
      saveAuth(){
        let allCheckedNodes = this.$refs.tree.getCheckedNodes()
        //全选中的节点
        let idList = allCheckedNodes.map(node => node.id);
        console.log(idList);
        //半选中的父节点id
        let parentIdList = this.$refs.tree.getHalfCheckedKeys();
        const assignMenuDTO = {
          roleId: this.assignRoleId,
          menuIdList: idList.concat(parentIdList)
        }
        sysRoleApi.doAssign(assignMenuDTO)
        .then(response =>{
          this.$message({
            type: 'success',
            message: '分配菜单成功!'
          });
          this.dialogAssignVisible = false
          this.fetchData()
        })
      },
        switchStatus(row){
            row.status = row.status === 1?0:1
            sysRoleApi.updateRoleStatus(row.id,row.status)
            .then(response =>{
                this.$message({
                type: 'success',
                message: '操作成功!'
            });
            //刷新
            this.fetchData()
        })
        },
        openDialogForm(roleId){
            if(roleId == undefined){
                this.dialogFormTitle = "添加角色"
            }else{
                this.dialogFormTitle = "修改角色"
                sysRoleApi.getRoleById(roleId)
                .then(response =>{
                    this.form = response.data
                    console.log(this.form);
                    this.status = this.form.status == 1 ? true : false
                })
            }
            this.dialogFormVisible = true
        },
        //添加修改表单
        addOrUpdate(formName){
        this.$refs[formName].validate((valid) => {
            if (valid) {
                if(this.status){
                    this.form.status = 1
                }else{
                    this.form.status = 0
                }
                if(this.form.id == undefined || this.form.id == ''){
                    sysRoleApi.saveRole(this.form)
                    .then(response =>{
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                    this.dialogFormVisible = false
                    //刷新
                    this.fetchData()
                    })
                }else{
                    sysRoleApi.updateRole(this.form)
                    .then(response =>{
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.dialogFormVisible = false
                    //刷新
                    this.fetchData()
                    })
                }
            } else {
            console.log('error submit!!');
            return false;
            }
        })},
        resetForm(form){
            this.$refs[form].resetFields();
            this.form= {}
            this.dialogFormVisible = false
        },
      fetchData() {
        sysRoleApi
          .getSysRolePageList(this.pageNum, this.pageSize, this.searchObj)
          .then((response) => {
            this.list = response.data.records;
            this.total = response.data.total;
          });
      },
      //改变每页显示记录数
      changePageSize(size) {
        this.pageSize = size;
        this.fetchData();
      },
      //改变页码数
      changeCurrentPage(page) {
        this.pageNum = page;
        this.fetchData();
      },

      resetData() {
        this.searchObj = {}
        this.fetchData()
      },
      //复选框发生变化
      handleSelectionChange(selection){
        this.multipleSelection = selection
        console.log(this.multipleSelection)
      },
      //删除单条信息
    removeById(id){
      this.$confirm('此操作将永久删除该条信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sysRoleApi.removeRoleById(id)
          .then((response) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //刷新
            this.fetchData()
          })
        });
    },
    //批量删除
    batchRemove(){
      //判断非空
      if(this.multipleSelection.length===0){
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idList =[]
          //遍历数组
          this.multipleSelection.forEach(item => {
            idList.push(item.id)
          })
          sysRoleApi.batchRemove(idList)
          .then((response) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //刷新
            this.fetchData()
          })
        });

    },
    }
}

</script>

<style>

</style>